<?php

/**
 * Export Category data to xml data 
 *
 * @category   Magestore
 * @package    Magestore_Mageconnector
 * @author     Nguyen Minh Dung (http://oss.com.vn)
 */
class Magestore_Mageconnector_Model_Cart extends Magestore_Mageconnector_Model_Abstract {

    /**
     * Initialize product instance from request data
     *
     * @return Mage_Catalog_Model_Product || false
     */
    protected function _initProduct() {
        $productId = (int) $_REQUEST['product'];
        if ($productId) {
            try {
                $view_code = $_REQUEST['view'];
            } catch (Exception $e) {
                $view_code = '';
            }
            $store = $this->getStore($view_code);
            $storeId = $store['store_id'];

            $product = Mage::getModel('catalog/product')
                            ->setStoreId($storeId)
                            ->load($productId);
            if ($product->getId()) {
                return $product;
            }
        }
        return false;
    }

    public function addToCart($baseUrl, $storeCode) {
        $store = $this->getStore($baseUrl, $storeCode);
        Mage::app()->setCurrentStore($store);

        $cart = Mage::getSingleton('checkout/cart');
        $params = $_REQUEST;
        try {
            if (isset($params['qty'])) {
                $filter = new Zend_Filter_LocalizedToNormalized(
                                array('locale' => Mage::app()->getLocale()->getLocaleCode())
                );
                $params['qty'] = $filter->filter($params['qty']);
            }

            $product = $this->_initProduct();
            try {
                $related = $params['related_product'];
            } catch (Exception $e) {
                $related = null;
            }

            /**
             * Check product availability
             */
            if (!$product) {
                return false;
            }

            $cart->addProduct($product, $params);
            if (!empty($related) && !is_null($related)) {
                $cart->addProductsByIds(explode(',', $related));
            }

            $cart->save();
            Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

            return true;
        } catch (Exception $e) {
            
        }
        return false;
    }

    public function updateCart($baseUrl, $storeCode) {
        $store = $this->getStore($baseUrl, $storeCode);
        Mage::app()->setCurrentStore($store);
        try {
            $cartData = $_REQUEST['cart'];
            if (is_array($cartData)) {
                $filter = new Zend_Filter_LocalizedToNormalized(
                                array('locale' => Mage::app()->getLocale()->getLocaleCode())
                );
                foreach ($cartData as $index => $data) {
                    if (isset($data['qty'])) {
                        $cartData[$index]['qty'] = $filter->filter($data['qty']);
                    }
                }
                $cart = Mage::getSingleton('checkout/cart');
                if (!$cart->getCustomerSession()->getCustomer()->getId() && $cart->getQuote()->getCustomerId()) {
                    $cart->getQuote()->setCustomerId(null);
                }
                $cart->updateItems($cartData)
                        ->save();
            }
            Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
            return true;
        } catch (Exception $e) {

        }
        return false;
    }

    public function deleteCartItem($baseUrl, $storeCode) {
        $store = $this->getStore($baseUrl, $storeCode);
        Mage::app()->setCurrentStore($store);
        $id = $_REQUEST['item'];
        if ($id) {
            try {
                $cart = Mage::getSingleton('checkout/cart')->removeItem($id)
                                ->save();
                return true;
            } catch (Exception $e) {
                
            }
        }
        return false;
    }

    /**
     * Get Cart data by store view
     *
     * @param string $baseUrl
     * @param string $storeCode
     */
    public function getCartData($baseUrl, $storeCode) {
        return $this->exportXml($baseUrl, $storeCode);
    }

    public function exportXml($baseUrl, $storeCode) {
        $store = $this->getStore($baseUrl, $storeCode);
        Mage::app()->setCurrentStore($store);
        $cartXML = '<?xml version="1.0" encoding="UTF-8"?><massale-cart>';

        $quote = Mage::getSingleton('checkout/session')->getQuote();
        $items = $quote->getAllVisibleItems();

        if (count($items) > 0) {
            $cartXML .= '<products>';
            $i = 0;
            foreach ($items as $item) {
                $product = $item->getProduct();

                switch ($product->getTypeId()) {
                    case "configurable":
                        $blockId = "checkout/cart_item_renderer_configurable";
                        break;
                    case "bundle":
                        $blockId = "bundle/checkout_cart_item_renderer";
                        break;
                    case "downloadable":
                        $blockId = "downloadable/checkout_cart_item_renderer";
                        break;
                    default:
                        $blockId = "checkout/cart_item_renderer";
                }

                $block = Mage::getBlockSingleton($blockId)
                                ->setItem($item);

                $cartXML .= '<product>'
                        . '<order>#' . (++$i) . '</order>'
                        . '<id>' . $block->getItem()->getId() . '</id>'
                        . '<name><![CDATA[' . $block->htmlEscape($block->getProductName()) . ']]></name>'
                        . '<image><![CDATA[' . $block->getProductThumbnail() . ']]></image>'
                        . '<url_key><![CDATA[' . $product->getUrlKey() . ']]></url_key>';

                if ($_options = $block->getOptionList()):
                    $cartXML .= '<options>';
                    foreach ($_options as $_option):
                        $_formatedOptionValue = $block->getFormatedOptionValue($_option);
                        $cartXML .= '<option>'
                                . '<label><![CDATA[' . $block->htmlEscape($_option['label']) . ']]></label>'
                                . '<value><![CDATA[' . $_formatedOptionValue['value'] . ']]></value>'
                                . '</option>'
                        ;
                    endforeach;
                    $cartXML .= '</options>';
                endif;

                $cartXML .= '<qty>' . $item->getQty() . '</qty>';

                $price = Mage::helper('core')
                                ->currency($item->getPrice(), true, false);
                $rowsubtotal = Mage::helper('core')
                                ->currency($item->getRowTotal(), true, false);

                $cartXML .= '<price><![CDATA[' . $price . ']]></price>';
                $cartXML .= '<subtotal><![CDATA[' . $rowsubtotal . ']]></subtotal>';
                $cartXML .= '</product>';
            }
            $cartXML .= '</products>';
            $cartXML .= '<hasCoupon>'.$quote->getCouponCode() != ''.'</hasCoupon>';

            $quoteTotals = $quote->getTotals();
            $cartXML .= '<totals>';
            foreach ($quoteTotals as $k => $v) {
                $cartXML .= '<' . $k . '>';
                $cartXML .= '<title><![CDATA[' . $v->title . ']]></title>';
                $cartXML .= '<value><![CDATA[' . Mage::helper('core')
                            ->currency($v->value, true, false) . ']]></value>';
                $cartXML .= '</' . $k . '>';
            }
            $cartXML .= '</totals>';
        } else {
            $cartXML .= 'empty';
        }
        $cartXML .= '</massale-cart>';
        return $cartXML;
    }

    public function applyCoupon($baseUrl, $storeCode) {
        $store = $this->getStore($baseUrl, $storeCode);
        Mage::app()->setCurrentStore($store);
        if (!Mage::getSingleton('checkout/cart')->getQuote()->getItemsCount()) {
            return false;
        }

        $couponCode = $_REQUEST['coupon_code'];
        $oldCouponCode = Mage::getSingleton('checkout/cart')->getQuote()->getCouponCode();

        if (!strlen($couponCode) && !strlen($oldCouponCode)) {
            return false;
        }

        try {
            Mage::getSingleton('checkout/cart')->getQuote()->getShippingAddress()->setCollectShippingRates(true);
            Mage::getSingleton('checkout/cart')->getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '')
                    ->collectTotals()
                    ->save();

            if ($couponCode) {
                if ($couponCode == Mage::getSingleton('checkout/cart')->getQuote()->getCouponCode()) {
                    return true;
                }
            }
        } catch (Exception $e) {

        }

        return false;
    }

    public function cancelCoupon($baseUrl, $storeCode) {
        $store = $this->getStore($baseUrl, $storeCode);
        Mage::app()->setCurrentStore($store);
        try {
            Mage::getSingleton('checkout/cart')->getQuote()->getShippingAddress()->setCollectShippingRates(true);
            Mage::getSingleton('checkout/cart')->getQuote()->setCouponCode('')
                    ->collectTotals()
                    ->save();

            return true;
        } catch (Exception $e) {

        }

        return false;
    }

    public function getCheckoutPage($baseUrl, $storeCode = null) {
        $store = $this->getStore($baseUrl, $storeCode);
        Mage::app()->setCurrentStore($store);
        $checkoutUrl = Mage::getBaseUrl() . 'checkout/';
        return $checkoutUrl;
    }

}